package com.simon.nearbyfootball.app.adapter;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.simon.nearbyfootball.app.AppFactoryConfig;
import com.simon.nearbyfootball.app.bean.JsonBean;
import com.simon.nearbyfootball.app.bean.DeviceInfo;
import com.simon.nearbyfootball.app.bean.SportsFrontQuery;
import com.simon.nearbyfootball.misc.Logger;
import com.simon.nearbyfootball.misc.VolleyUtil;

import android.app.Activity;

public class ApiClient {

	private static void postJsonRequest(Activity activity, String url,
			final JsonBean requestParam, Listener<String> listener,
			ErrorListener errorListener) {
		VolleyUtil.getQueue(activity).cancelAll(activity);
		StringRequest request = new StringRequest(Method.POST, url, listener,
				errorListener) {

			@Override
			public byte[] getBody() throws AuthFailureError {
				// TODO Auto-generated method stub
				JSONObject jsonBody = new JSONObject();
				if(requestParam != null){
					try {
						requestParam.generateJsonObj(jsonBody);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				try {
					DeviceInfo.getinstance().generateJsonObj(jsonBody);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Logger.finetrace("Send request body is:" + jsonBody.toString());
				
				return jsonBody.toString().getBytes();
			}

		};

		request.setTag(activity);
		VolleyUtil.getQueue(activity).add(request);
	}

	/**
	 * @param activity
	 * @param query
	 * @param listener
	 * @param errorListener
	 */
	public static void getSportFontList(Activity activity,
			SportsFrontQuery query, Listener<String> listener,
			ErrorListener errorListener) {
		String url = AppFactoryConfig.getUrl(AppFactoryConfig.getHost(),
				AppFactoryConfig.getQueryPlaceConfig());
		postJsonRequest(activity, url, query, listener, errorListener);
	}
}
